import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_module/res/colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:image_picker/image_picker.dart';
import '../channel/ChannelConstant.dart';
import '../channel/extremely_rich_channel.dart';
import '../log/log_util.dart';

typedef PhotoCallback = void Function(Image, String, Uint8List);

class PhotoSelectorUtil {
  VoidCallback? removeListener;
  PhotoCallback? photoCallback;

  static final PhotoSelectorUtil _instance = PhotoSelectorUtil._internal();

  factory PhotoSelectorUtil() => _instance;

  PhotoSelectorUtil._internal();

  static const showPhotoTag = "showPhotoSelector";

  /// 裁剪比例宽度
  static const cropRatioX = 1.0;

  ///裁剪比例高度
  static const cropRatioY = 1.35;

  ///图片压缩大小
  static const cropByte = 1024 * 1024 * 20;

  void showPhotoSelector({PhotoCallback? callback}) {
    photoCallback = callback;
    locationDialog({
      required Alignment alignment,
      double width = double.infinity,
    }) {
      _listener();
      SmartDialog.show(
        tag: showPhotoTag,
        alignment: alignment,
        builder: (_) => Container(
          width: width,
          decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.vertical(top: Radius.circular(8))),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildText("拍照", onPressed: () {
                openCamera();
              }),
              _buildText("从相册中选择", onPressed: () {
                openPhoto();
              }),
              _buildText("取消", onPressed: () {
                _dismiss();
                removeListener?.call();
              }),
            ],
          ),
        ),
      );
    }

    locationDialog(alignment: Alignment.bottomCenter);
  }

  _buildText(String text, {VoidCallback? onPressed}) {
    return SizedBox(
      width: double.infinity,
      height: 55,
      child: TextButton(
        onPressed: onPressed,
        child: Text(
          text,
          style: const TextStyle(color: YouthColors.color_170606, fontSize: 16),
        ),
      ),
    );
  }

  openCamera() async {
    final ImagePicker picker = ImagePicker();
    final XFile? photo = await picker.pickImage(source: ImageSource.camera);
    logger.d("photo ${photo?.path}");
    String? path = photo?.path;
    if (path?.isNotEmpty == true) {
      ExtremelyRichChannel.instance.sendEventToNative(CHANNEL_EVENT_NATIVE_FUNCTION, {
        KEY_PHOTO_CROP: {
          PARAM_PHOTO_PATH: path,
          PARAM_CROP_RATIO_X: cropRatioX,
          PARAM_CROP_RATIO_Y: cropRatioY,
          PARAM_COMPRESS_BYTE: cropByte,
        },
      });
    }
    _dismiss();
  }

  openPhoto() async {
    ExtremelyRichChannel.instance.sendEventToNative(CHANNEL_EVENT_NATIVE_FUNCTION, {
      KEY_OPEN_ALBUM: {
        PARAM_ALBUM_NUMBER: "1",
        PARAM_ALBUM_CUT: true,
        PARAM_CROP_RATIO_X: cropRatioX,
        PARAM_CROP_RATIO_Y: cropRatioY,
        PARAM_COMPRESS_BYTE: cropByte,
      },
    });
    _dismiss();
  }

  void _listener() {
    removeListener = ExtremelyRichChannel.instance.addEventListener(
        CHANNEL_EVENT_NATIVE_FUNCTION_RECEIVE, (key, arguments) {
      var photoBase64 = arguments[KEY_PHOTO_BASE64];
      Uint8List bytes = base64Decode(photoBase64);
      Image image = Image.memory(bytes);
      var tempFileName = "image_${DateTime.now().millisecond}.jpg";
      photoCallback?.call(image, tempFileName, bytes);
      return Future(() => "");
    });
  }

  void _dismiss() {
    SmartDialog.dismiss(tag: showPhotoTag);
  }

  // Future<void> _compressFile(String? path) async {
  //   YZAliyunImage.compressAndGetFile(File(path ?? ''), ((p0, p1) {
  //     _dismiss();
  //   }));
  // }
}
